package com.leslie.hhcommunity.controller.interceptor;

import com.leslie.hhcommunity.annotation.LoginRequired;
import com.leslie.hhcommunity.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author
 * @PackageName:com.leslie.hhcommunity.controller.interceptor
 * @ClassnName:LoginRequiredInterceptor
 * @Description:
 * @Date 2022/1/3  11:32
 */
@Deprecated
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {

	@Autowired
	private HostHolder hostHolder;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
		if (handler instanceof HandlerMethod){
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
			if (loginRequired != null && hostHolder.getUser() == null){
				response.sendRedirect(request.getContextPath() + "/toLogin");
				System.out.println("拦截了");
				return false;
			}
		}
		return true;
	}
}
